const app = getApp();
const userApi = require('../../api/user.js');

Page({

  data: {
    userInfo: {
      nickname: '用户12345',
      avatar: 'https://cdn-icons-png.flaticon.com/512/149/149071.png',
      status: '0',
      credit: 60,
    }
  },

  onLoad() {
    if (!app.globalData.hasLogin) {
      wx.showToast({ title: '请先登录', icon: 'none' });
      setTimeout(() => {
        wx.redirectTo({ url: '/pages/login/login' });
      }, 1500);
      return;
    }
    this.loadData();
  },
  async loadData() {
      const res = await userApi.getUser();
      console.log("用户信息：", res.data);
      let userInfo = res.data.data;
      if (!userInfo.avatar || userInfo.avatar === 'undefined') {
        userInfo.avatar = 'https://cdn-icons-png.flaticon.com/512/149/149071.png';
      }
      this.setData({ userInfo });
      wx.setStorageSync('userInfo', JSON.stringify(userInfo));
  },

  chooseAvatar() {
    const that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'], 
      sourceType: ['album', 'camera'], 
      success(res) {
        const tempFilePath = res.tempFilePaths[0]; 
        that.uploadAvatar(tempFilePath);
      }
    });
  },

  async uploadAvatar(filePath) {
      wx.showLoading({ title: '上传中...' });
      const res = await new Promise((resolve, reject) => {
        wx.uploadFile({
          url: userApi.baseUrl + '/updateAvatar', 
          filePath: filePath,
          name: 'file', 
          formData: {}, 
          success: (res) => resolve(JSON.parse(res.data)),
          fail: (err) => reject(err),
          complete: () => wx.hideLoading()
        });
      });

      if (res.code === 200) {
        wx.showToast({ title: '头像更换成功' });
        this.setData({ 'userInfo.avatar': res.data.avatar });
        this.loadData(); 
      } else {
        wx.showToast({ title: '头像更换失败', icon: 'none' });
      }
  },

  handleBack() {
    wx.navigateBack({ delta: 1 });
  },

  navigateToProfile() {
    wx.navigateTo({ url: '/pages/profile/profile' });
  },

  navigateToCertification() {
    wx.navigateTo({ url: '/pages/certification/certification' });
  },

  navigateToOrders() {
    wx.navigateTo({ url: '/pages/user/orders/orders' });
  },

  navigateToSignIn() {
    wx.navigateTo({ url: '/pages/signIn/signIn' });
  },
  navigateToWallet() {
    wx.navigateTo({ url: '/pages/wallet/wallet' });
  },
  handleLogout() {
    const that = this;
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      confirmText: '确定',
      cancelText: '取消',
      success: async function(res) {
        if (res.confirm) {
          try {
            const res = await userApi.exit();
            if (res.code === 200) {
              wx.showToast({ title: '退出登录成功' });
              wx.removeStorageSync('userInfo');
              wx.removeStorageSync('token');
              app.globalData.hasLogin = false;
              app.globalData.token = '';
              setTimeout(() => {
                wx.switchTab({ url: '/pages/index/index' });
              }, 1500);
            }
          } catch (err) {
            console.error('退出登录失败：', err);
            wx.showToast({ title: '退出失败，请重试', icon: 'none' });
          }
        } else {
          wx.showToast({ title: '已取消退出', icon: 'none' });
        }
      }
    });
  }
});